#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int N = 1000000, HN = 1000003;
int head[HN], next[N];
int st[N][9], goal[9];
int dis[N];
const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
 
int Hash(int *st) {
	int v = 0;
	for(int i = 0; i < 9; i++)
		v = v*10 + st[i];
	return v % HN;
}
 
bool try_insert(int rear) {
	int h = Hash(st[rear]);
	int u = head[h];
	while(u) {
		if(!memcmp(st[u], st[rear], sizeof(st[0])))
			return 0;
		u = next[u];
	}
	next[rear] = head[h];
	head[h] = rear;
	return 1;
}
 
int bfs() {
	memset(head, 0, sizeof(head));
	int fron = 1, rear = 2;
	while (fron < rear) {
		if (!memcmp(goal, st[fron], sizeof(st[0])))
		    return fron;
		int z;
		for(z = 0; z < 9; z++)
		if(!st[fron][z])
			break;
		int x = z / 3, y = z % 3;
		for(int d = 0; d < 4; d++) {
			int nx = x + dx[d], ny = y + dy[d], nz = 3*nx + ny;
			if(nx >= 0&&nx < 3&&ny >= 0&&ny < 3) {
				memcpy(&st[rear], &st[fron], sizeof(st[0]));
				st[rear][nz] = st[fron][z];
				st[rear][z] = st[fron][nz];
				dis[rear] = dis[fron] + 1;
				if(try_insert(rear))
					rear++;
			}
		}
		fron++;
	}
	return 0;
}
 
int main() {
	for(int i = 0; i < 9; i++)
		scanf("%d", &st[1][i]);
	for(int i = 0; i < 9; i++)
		scanf("%d", &goal[i]);
	int ans = bfs();
	if(ans > 0)
		printf("%d\n", dis[ans]);
	else
		puts("-1");
	return 0;
}
